package com.tian.library.permission

import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2020/12/10 19:11
 */
class TianPermission private constructor(private val mActivity: FragmentActivity?){

    companion object {
        /** 权限设置页跳转请求码 */
        const val REQUEST_CODE = 11024
        const val TAG = "TianPermission"

        fun with(activity: FragmentActivity): TianPermission {
            return TianPermission(activity)
        }

        fun with(context: Context): TianPermission {
            return TianPermission(PermissionUtil.getFragmentActivity(context))
        }

        fun with(fragment: Fragment): TianPermission {
            return TianPermission(fragment.activity)
        }

        fun startApplicationDetails(activity: Activity) {
            activity.startActivityForResult(PermissionSettingPage.getApplicationDetailsIntent(activity), REQUEST_CODE)
        }

        fun startPermissionActivity(activity: Activity, permissions: MutableSet<String>) {
            activity.startActivityForResult(PermissionSettingPage.getSmartPermissionIntent(activity, permissions), REQUEST_CODE)
        }

    }

    private var mPermissions: MutableSet<String> = mutableSetOf()


    /**
     * 设置权限组
     */
    fun permission(vararg permissions: String): TianPermission {
        mPermissions.addAll(permissions)
        return this
    }

    /**
     * 设置权限组
     */
    fun permission(vararg permissions: Array<String>): TianPermission{
         for (permission in permissions) {
             mPermissions.addAll(permission.toMutableList())
         }
        return this
    }

    /**
     * 设置权限组
     */
    fun permission(permissions: MutableList<String>): TianPermission{
        mPermissions.addAll(permissions)
        return this
    }

    /**
     * 请求权限
     */
    fun request(callback: OnPermissionCallback?) {
        // 如果传入 Activity 为空或者 Activity 状态非法则直接屏蔽这次权限申请
        if (mActivity == null || mActivity?.isFinishing || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity?.isDestroyed) ) {
            return
        }

        // 必须要传入权限或者权限组才能申请权限
        if (mPermissions.isEmpty()) {
            Log.e(TAG, "The requested permission cannot be empty")
            return
        }

        // 优化所申请的权限列表
        PermissionUtil.optimizeDeprecatedPermission(mPermissions)

        if (PermissionUtil.isGrantedPermission(mActivity, mPermissions)) {
            callback?.onGranted(mPermissions, true)
            return
        }

        // 申请没有授予过的权限
        PermissionFragment.beginRequest(mActivity, mPermissions, callback)
    }


}